import Vue from 'vue';
import Vuex from 'vuex';
import { getSideBar, getGoodsList } from '@/apis';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    originSideBar: [],
    loading: false,
    goodsList: [],
    pageSize: 5,
    goodsType: null,
    counterMap: {},
    shopCartDom: null,
  },
  getters: {
    sideBar(state) {
      const category = state.originSideBar[0];
      const list = state.originSideBar.slice(1);
      list.category = category;
      if (list.length > 0) list.unshift('全部');
      return list;
    },
    totalCart(state) {
      return Object.values(state.counterMap).reduce((prev, next) => prev + next, 0);
    },
  },
  mutations: {
    setSideBar(state, list) {
      state.originSideBar = list;
    },
    setLoading(state, status) {
      state.loading = status;
    },
    appendGoodsList(state, list) {
      state.goodsList = [...state.goodsList, ...list];
    },
    setGoodsList(state, list) {
      state.goodsList = list;
    },
    setGoodsType(state, type) {
      state.goodsType = type;
    },
    setCounterMap(state, map) {
      state.counterMap = map;
    },
    changeStorage(state, { id, value }) {
      if (state.counterMap[id]) {
        if (value === -1 && state.counterMap[id] === 1) Vue.delete(state.counterMap, id);
        else Vue.set(state.counterMap, id, state.counterMap[id] + value);
      } else {
        Vue.set(state.counterMap, id, 1);
      }
      localStorage.setItem('goods', JSON.stringify(state.counterMap));
    },
    setShopCartDom(state, dom) {
      state.shopCartDom = dom;
    },
  },
  actions: {
    async fetchSideBar({ commit }, type) {
      commit('setSideBar', []);
      const timer = setTimeout(() => {
        commit('setLoading', true);
      }, 500);
      const data = await getSideBar(type);
      commit('setSideBar', data);
      clearTimeout(timer);
      commit('setLoading', false);
    },
    async fetchGoodsList({ commit, state }, {
      type, page, sort, append = false,
    }) {
      const data = await getGoodsList(type, page, state.pageSize, sort);
      console.log(data);
      if (type) commit('setGoodsType', type);
      if (append) {
        commit('appendGoodsList', data.list);
      } else {
        commit('setGoodsList', data.list);
      }
      return data.total > state.goodsList.length;
    },
  },
  modules: {
  },
});
